<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="">
    <div class="container1">
      <el-card class="mb-6">
        <span class="text-lg font-medium mb-3">模块简介：</span>
        <span class="text-gray-600 leading-relaxed mt-8">
          自动下载收集来自国际的多个气象预报中心的开源数值分析产品结果（包括欧洲中期天气预报中心ERA5再分析气象数据、CCMP再分析气象数据等），下载参数包括10m高度风速、风向、气压、气温、湿度，数据时间跨度40年，时间分辨率3小时。
        </span>
      </el-card>
      <el-card class="mb-6">
        <div class="flex items-center justify-between">
          <span class="text-lg font-medium">自动下载程序</span>
          <div class="flex items-center space-x-4">
            <el-button
              type="primary"
              class="!rounded-button whitespace-nowrap"
              size="small"
              @click="toggleViewCode"
            >查看</el-button>
          </div>
        </div>
      </el-card>
      <el-card class="h-full">
        <el-tabs v-model="activeTab">
          <el-tab-pane
            label="要素图"
            name="chart"
            class="flex-1 flex flex-col h-full"
          >
            <div class="flex items-center justify-between mb-6">
              <div class="flex items-center space-x-6">
                <div class="flex items-center space-x-2">
                  <span class="text-gray-600 flex-shrink-0">数据源：</span>
                  <el-select v-model="selectedSource" size="small">
                    <el-option
                      v-for="source in sourceOptions"
                      :key="source"
                      :label="source"
                      :value="source"
                    />
                  </el-select>
                </div>
                <div class="flex items-center space-x-2">
                  <span class="text-gray-600 flex-shrink-0">参数：</span>
                  <el-select v-model="selectedType" size="small">
                    <el-option
                      v-for="type in typeOptions"
                      :key="type"
                      :label="type"
                      :value="type"
                    />
                  </el-select>
                </div>
                <div class="flex items-center space-x-2">
                  <span class="text-gray-600 flex-shrink-0">日期：</span>
                  <el-date-picker
                    size="small"
                    v-model="selectedDate"
                    type="date"
                    class="w-40"
                  />
                </div>
                <div class="flex items-center space-x-2">
                  <span class="text-gray-600 flex-shrink-0">时间：</span>
                  <el-select v-model="selectedTime" size="small" class="w-100">
                    <el-option
                      v-for="time in timeOptions"
                      :key="time"
                      :label="time"
                      :value="time"
                    />
                  </el-select>
                </div>
              </div>
              <div class="flex items-center space-x-4">
                <el-button type="primary" @click="handleSearch" size="small">
                  <i class="el-icon-search"></i>查询
                </el-button>
                <el-button @click="handleReset" size="small">
                  <i class="el-icon-refresh"></i>重置
                </el-button>
              </div>
            </div>
            <!-- 图片预览区域 -->
            <div
              class="w-full aspect-[16/9] bg-gray-100 rounded-lg flex items-center justify-center mt-10 p-10"
              style="height: 60vh"
            >
              <div
                v-if="previewImage"
                class="w-full h-full flex items-center justify-center"
              >
                <img :src="previewImage" class="h-full" />
              </div>
              <div v-else class="text-center">
                <i class="el-icon-picture text-gray-400 text-6xl mb-4"></i>
                <p class="text-gray-500">暂无数据</p>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="数据查看" name="download" class="flex-1">
            <!-- 文件列表 -->
            <div class="overflow-y-auto pr-2" style="height: 65vh">
              <iframe
                :src="currentIframeUrl"
                class="w-full h-full border-none rounded-lg bg-gray-50"
                :title="`${selectedSource}数据文件目录`"
                loading="lazy"
              ></iframe>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <el-dialog :visible.sync="isModalOpen" title="自动下载程序">
        <div id="codeContent">
          <pre><code>{{ code }}</code></pre>
        </div>
      <template slot="footer">
        <el-button @click="closeModal"  size="small" >关闭</el-button>
        <el-button type="primary" size="small" @click="copyCode">一键复制</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from "element-ui";
export default {
  data() {
    const DATASTORE_BASE_URL = "https://datastore.iocean.cn";
    const ERA5_PATH = "/era5_reanalysis/";
    const CCMP_PATH = "/ccmp_reanalysis/";
    const PIC_BASE_PATH = "/Media/pics/";

    return {
      isModalOpen: false,
      code:'',
      activeTab: "chart",
      previewImage:null,
      selectedTime: "00",
      selectedType: "风速风向",
      selectedSource: "ERA5",
      selectedDate: new Date(),
      timeOptions: Array.from({ length: 24 }, (_, i) =>
        i.toString().padStart(2, "0")
      ),
      typeOptions: ["风速风向", "气压", "气温", "湿度"],
      sourceOptions: ["ERA5", "CCMP"],
      files: Array.from({ length: 50 }, (_, index) => ({
        name: `ERA5_WindSpeed_${2023 - Math.floor(index / 12)}_${(
          (index % 12) +
          1
        )
          .toString()
          .padStart(2, "0")}.nc`,
      })),
      urlMappings: {
        ERA5: {
          "风速风向": `${DATASTORE_BASE_URL}${ERA5_PATH}wind/`,
          "气压": `${DATASTORE_BASE_URL}${ERA5_PATH}msl/`,
          "气温": `${DATASTORE_BASE_URL}${ERA5_PATH}d2m/`,
          "湿度": `${DATASTORE_BASE_URL}${ERA5_PATH}water/`
        },
        CCMP: {
          "风速风向": `${DATASTORE_BASE_URL}${CCMP_PATH}wind/`,
          "气压": `${DATASTORE_BASE_URL}${CCMP_PATH}msl/`,
          "气温": `${DATASTORE_BASE_URL}${CCMP_PATH}d2m/`,
          "湿度": `${DATASTORE_BASE_URL}${CCMP_PATH}water/`
        }
      },
      picMappings: {
        ERA5: {
          "风速风向": `${DATASTORE_BASE_URL}${ERA5_PATH}${PIC_BASE_PATH}wind/`,
          "气压": `${DATASTORE_BASE_URL}${ERA5_PATH}${PIC_BASE_PATH}msl/`,
          "气温": `${DATASTORE_BASE_URL}${ERA5_PATH}${PIC_BASE_PATH}d2m/`,
          "湿度": `${DATASTORE_BASE_URL}${ERA5_PATH}${PIC_BASE_PATH}water/`
        },
        CCMP: {
          "风速风向": `${DATASTORE_BASE_URL}${CCMP_PATH}${PIC_BASE_PATH}wind/`,
          "气压": `${DATASTORE_BASE_URL}${CCMP_PATH}${PIC_BASE_PATH}msl/`,
          "气温": `${DATASTORE_BASE_URL}${CCMP_PATH}${PIC_BASE_PATH}d2m/`,
          "湿度": `${DATASTORE_BASE_URL}${CCMP_PATH}${PIC_BASE_PATH}water/`
        }
      },
      picNameTemplate: {
        "风速风向": "ERA5_wind10_105E125E10N25N_",
        "气压": "ERA5_msl_105E125E10N25N_",
        "气温": "ERA5_d2m_105E125E10N25N_",
        "湿度": "ERA5_water_105E125E10N25N_"
      }
    };
  },
  computed: {
    currentIframeUrl() {
      return this.urlMappings[this.selectedSource][this.selectedType];
    }
  },
  created() {
    // 数据初始化后立即执行一次查询
    this.handleSearch();
  },
  methods: {
    copyCode() {
      navigator.clipboard.writeText(this.code).then(() => {
         Message({ message: '代码已复制到剪贴板', type: "success" });
      }).catch((error) => {
         Message({ message: '复制代码时出错', type: "error" });
      });
    },
    closeModal() {
      this.isModalOpen = false;
    },
   async toggleViewCode() {
      try {
        const response = await fetch('/index.html');
        if (!response.ok) {
          throw new Error('无法获取index.html文件');
        }
        this.code = await response.text();
        this.isModalOpen = true;
      } catch (error) {
        console.error('加载代码时出错:', error);
      }
    },
    async handleSearch() {
      try {
        if (!this.picMappings || !this.picMappings[this.selectedSource] || !this.picMappings[this.selectedSource][this.selectedType]) {
          throw new Error('图片映射配置不完整');
        }

        const dateStr = this.formatDate(this.selectedDate);
        const picBaseUrl = this.picMappings[this.selectedSource][this.selectedType];
        const picName = `${this.picNameTemplate[this.selectedType]}${dateStr}${this.selectedTime}.JPG`;
        const imageUrl = `${picBaseUrl}${dateStr}/${picName}`;

        // 检查图片是否存在
        const imgExists = await this.checkImageExists(imageUrl);
        if (imgExists) {
          this.previewImage = imageUrl;
          console.log("图片加载成功:", this.previewImage);
        } else {
          this.previewImage = null;
          // Message.warning('未找到对应图片数据');
        }
      } catch (error) {
        console.error("加载图片时出错:", error);
        this.previewImage = null;
        Message.error('加载图片失败，请检查参数配置');
      }
    },
    async checkImageExists(url) {
      return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => resolve(true);
        img.onerror = () => resolve(false);
        img.src = url;
      });
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}${month}${day}`;
    },
    handleReset() {
      this.selectedTime = "00";
      this.selectedType = "风速风向";
      this.selectedSource = "ERA5";
      this.selectedDate = new Date();
    },
  },
};
</script>

<style scoped>
.container1 {
  height: calc(100vh - 70px);
}

.el-button {
  display: inlinas, Liberation Mono, Menlo, monospace;
  font-size: 14px;
}
pre {
  background-color: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
  font-size: 14px;
  line-height: 1.5;
  overflow: auto;
  max-height: 60vh;
  width: 100%;
  white-space: pre-wrap;
  word-wrap: break-word;
}

code {
  font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
  font-size: 14px;
  color: #333;
}

.hljs {
  display: block;
  overflow-x: auto;
  padding: 0.5em;
  background: #f6f8fa;
}

.hljs-keyword,
.hljs-built_in {
  color: #d73a49;
}

.hljs-string {
  color: #032f62;
}

.hljs-comment {
  color: #6a737d;
  font-style: italic;
}

.hljs-number {
  color: #005cc5;
}

.hljs-title,
.hljs-params {
  color: #6f42c1;
}
</style>
